#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include "log.hpp"

using namespace std;

const string path = "/home/silence";
const int proj_id = 666666;
const int SIZES = 4096;
Log log;

//key_t 就是int
//这个函数就是拿到key值，为了保证让不同的进程看到同一块资源
key_t Getkey()
{
    key_t key = ftok(path.c_str(),proj_id);
    if(key == -1)
    {
        //打开失败
        log(FATAL,"Getkey fail : %s",strerror(errno));
        exit(1);
    }
    log(INFO,"Getkey sucess key : %d",key);
    return key;
}

//申请共享内存
int Getsharememory(int flag)
{
    key_t key = Getkey();
    int shmid = shmget(key,SIZES,flag);
    if(shmid == -1)
    {
        //申请共享内存失败
        log(FATAL,"Getsharememory fail : %s",strerror(errno));
        exit(2);
    }
    log(FATAL,"Getsharememory sucess : %d",shmid);
    return shmid;
}

int Creatshm()
{
    return Getsharememory(IPC_CREAT|IPC_EXCL|0666);
}

int Getshm()
{
    return Getsharememory(IPC_CREAT);
}


#define FIFO_FILE "./myfifo"
#define MODE 0666

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {

        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};